<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref, computed, onUnmounted } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox, ElLink, ElMessageBox, ElMessage, ElIcon } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import {
  loginApi,
  getTestRoleApi,
  getAdminRoleApi,
  getSerialNumberApi,
  getIsRegisterApi,
  saveRegisterCodeApi
} from '@/api/login'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import { md5 } from 'js-md5'
const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()
const isshowlogo = computed(() => appStore.getLogo)
console.log('isshowlogo', isshowlogo.value)
const rules = {
  username: [required()],
  password: [required()]
}
let serialNumber = ''
const getSerialNumber = async () => {
  const res = await getSerialNumberApi()
  serialNumber = res.data || ''
}
// getSerialNumber()
const isRegister = ref(false)
const isNoRegister = ref()
// const getIsRegister = async () => {
//   const res = await getIsRegisterApi()
//   if (res) {
//     isRegister.value = res.data == -1
//     if (res.data == 0) {
//       isNoRegister.value = { ...res }
//     }

//     appStore.setTitle(
//       import.meta.env.VITE_APP_TITLE + `(有效期:${res.data == -1 ? '永久' : res.data + '天'})`
//     )
//   }
// }
console.log('title---', import.meta.env.VITE_APP_TITLE)

// getIsRegister()

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          const titile = import.meta.env.VITE_APP_TITLE
          return <h2 class="text-2xl font-bold text-center w-[100%] "> {titile}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    // label: t('login.username'),
    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入账号',
      prefixIcon: 'UserFilled'
    }
  },
  {
    field: 'password',
    // label: t('login.password'),
    // value: 'admin',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入密码',
      prefixIcon: 'Lock'
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('login.remember')} size="small" />
                {isRegister.value ? null : (
                  <ElLink type="primary" onClick={toRegister} underline={false}>
                    {t('login.register')}
                  </ElLink>
                )}
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])
//点击回车键登录
// const keyDown = (e) => {
//   let timer
//   if (e.keyCode == 13 || e.keyCode == 100) {
//     if (timer) {
//       clearTimeout(timer)
//     }
//     timer = setTimeout(async () => {
//       await signIn()
//     }, 300)
//   }
// }
// onMounted(() => {
//   //绑定监听事件
//   window.addEventListener('keydown', keyDown)
// })
// onUnmounted(() => {
//   //销毁事件
//   window.removeEventListener('keydown', keyDown, false)
// })
const toRegister = () => {
  // emit('to-register')
  ElMessageBox.prompt('请输入激活码', '序列号:' + serialNumber, {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
    // inputPattern: /^[a-zA-Z0-9_-]{4,29}$/,
    // inputErrorMessage: '激活格式不正确'
  }).then(async ({ value }) => {
    const res = await saveRegisterCodeApi({
      registerCode: value,
      serialNumber: serialNumber
    })
    if (res) {
      ElMessage.success('激活成功')
      isRegister.value = true
    }
  })
}

const iconSize = 30

const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
onMounted(() => {
  initLoginInfo()
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)

const iconColor = '#999'

const hoverColor = 'var(--el-color-primary)'

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  // if (isNoRegister.value) {
  //   ElMessage.error(isNoRegister.value?.msg || '请先激活')
  //   return
  // }
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserType>()
      let passwordnoMD5 = formData.password
      formData.password = md5(formData.password)
      try {
        const res = await loginApi(formData)

        if (res) {
          // 是否记住我
          if (unref(remember)) {
            userStore.setLoginInfo({
              username: formData.username,
              password: passwordnoMD5
            })
          } else {
            userStore.setLoginInfo(undefined)
          }
          userStore.setRememberMe(unref(remember))
          userStore.setUserInfo(res.data)
          userStore.setToken(res.data.token)
          // 是否使用动态路由
          await permissionStore.generateRoutes('server', res.data.role, res.data.roleId) // res.data.role
          permissionStore.getAddRouters.forEach((route) => {
            addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
          })
          permissionStore.setIsAddRouters(true)

          // push({
          //   path: redirect.value
          // })
          // console.log(
          //   'luyou',
          //   redirect.value,
          //   permissionStore.addRouters[0].path + permissionStore.addRouters[0]?.children[0]?.path
          // )
          push({
            path:
              redirect.value ||
              permissionStore.addRouters[0].path +
                '/' +
                permissionStore.addRouters[0]?.children[0]?.path
          })
          window.location.reload()
          //
          // +'/' + permissionStore.addRouters[0]?.children[0]?.path
          // push({
          //   path: redirect.value || permissionStore.addRouters[0].path
          // })
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div class="colorwhite">
    <!-- <dv-border-box-10 :color="['red', 'green']"> -->
    <Form
      style="padding: 30px"
      :schema="schema"
      :rules="rules"
      hide-required-asterisk
      size="large"
      @register="formRegister"
    />
    <!-- </dv-border-box-10> -->

    <!-- <div style="display: flex" v-if="isshowlogo">
      <img src="@/assets/imgs/blogo.png" style="width: 94px; height: 46px; margin: 0 auto" />
    </div> -->
  </div>
</template>
<!--  class="dark:(border-1 border-[var(--el-border-color)] border-solid)" -->
<style lang="css">
.colorwhite {
  background-color: white;
  border-radius: 8px;
}
</style>
